import RenderContext from "@/views/cg/lib/RenderContext.ts";
import GLVertexBuffer from "@/views/cg/lib/model/GLVertexBuffer.ts";
import GLIndexBuffer from "@/views/cg/lib/model/GLIndexBuffer.ts";

export class Mesh {
  constructor({vertexes, indices =null, dimension = 3, colors = null, texCoord, norms}) {
    this.dimension = dimension
    this.vertexes = vertexes
    this.indices = indices
    this.colors = colors
    this.norms = norms
    this.texCoord = texCoord
    //
    this.gl = RenderContext.getGL()
    this.program = RenderContext.getProgram()
    this.vertexBuffer = new GLVertexBuffer(
      'a_position',
      new Float32Array(vertexes),
      dimension
    )

    if(this.colors){
      this.colorsBuffer = new GLVertexBuffer(
        'a_color',
        new Float32Array(colors),
        dimension
      )
    }

    if(this.indices){
      this.indicesBuffer = new GLIndexBuffer(
        new Uint16Array(indices),
        dimension
      )
    }

    if(this.texCoord){
      this.texturesBuffer = new GLVertexBuffer(
        'a_texcoord',
        new Float32Array(texCoord),
        2
      )
    }

    if(this.norms){
      this.normsBuffer = new GLVertexBuffer(
        'a_norm',
        new Float32Array(norms),
        3
      )
    }
  }


  disableAttribute(name){
    this.disableSet.delete(name)
  }

  enableAttribute(name){
    this.disaleSet.add(name)
  }

  draw(){
    const gl = this.gl;
    gl.enable(gl.DEPTH_TEST)
    gl.depthFunc(gl.LEQUAL)

    // 应用
    this.vertexBuffer.associate()
    this.colorsBuffer && this.colorsBuffer.associate()
    this.indicesBuffer && this.indicesBuffer.associate()
    this.texCoord && this.texturesBuffer.associate()
    this.normsBuffer && this.normsBuffer.associate()

    if(this.indicesBuffer){
      gl.drawElements(
        gl.TRIANGLES,
        this.indices.length,
        gl.UNSIGNED_SHORT,
        0
      )
    }else{
      gl.drawArrays(
        gl.TRIANGLES,
        0,
        this.vertexes.length / this.dimension
      )
    }
  }
}
